<template>
  <div class="address-edit-box">
    <!--公用头部，通过type判断是新增还是编辑-->
    <custom-header :title="`${type =='add' ? '新增地址' : '编辑地址'}`"></custom-header>
    <!--Vant UI组件库提供的地址栏组件-->
    <van-address-edit 
      class="edit"
      :area-list="areaList"
      :address-info="addressInfo"
      :show-delete="type == 'edit'"
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择','请选择','请选择']"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>
<script>
import { reactive, onMounted, toRefs } from 'vue'
import { Toast } from 'vant'
import CustomHeader from 'components/CustomHeader.vue' //引入公用头部
import { addAddress, getAddressDetail, EditAddress, DeleteAddress  } from '@/service/address' //引入地址管理相应接口方法
import { useRoute } from 'vue-router' //引入路由方法

export default {
  components:{
    CustomHeader //注册组件
  },
  setup(){
    const route = useRoute() //生成route实例
    const state = reactive({
      //省，市，区对象
      areaList: {
        province_list: {}, //省份数据
        city_list: {}, //市级别数据
        county_list: {} //地区级别数据
      },
      searchResult: [],
      type: 'add', //add: 添加操作 edit:编辑操作
      addressId: '',
      addressInfo: {}
    })
    onMounted(() => {
      //初始化数据
      const { type } = route.query //获取类型
      state.type = type //赋值给type
      initData()
    })
    const initData = async() => {
      //省，市，区列表构造
      let _province_list = {} //省
      let _city_list = {} //市
      let _county_list = {} //区
      //通过tdist 的getLev1方法，获取省级数据，将id作为key，将text作为value，赋值给_province_list
      window.tdist.getLev1().forEach(p => {
        _province_list[p.id] = p.text
        //通过tdist的getLev2方法，获取市级数据，将id作为key，将text作为value，赋值给_city_list
        window.tdist.getLev2(p.id).forEach(c => {
          _city_list[c.id] = c.text
          //通过tdist的getLev3方法，获取区级数据，将id作为key将text作为value，赋值给_county_list
          window.tdist.getLev3(c.id).forEach(q => _county_list[q.id] = q.text)
        })
      })
      //使用上述代码，组装好AddressEdit所需area-list数据后，赋值给相应的变量
      state.areaList.province_list = _province_list
      state.areaList.city_list = _city_list 
      state.areaList.county_list = _county_list

      const { type, addressId } = route.query //获取类型
      state.type = type //赋值给type
      if(addressId && type == 'edit'){
        state.addressId = addressId
        addressDetail()
      }
    }

    //保存方法，注意AddressEdit组件的save方法，会返回填入的数据作为参数，下面content便是address-info的值
    const  onSave = async (content) => {
      const params = {
        userName: content.name, //收件人
        userPhone: content.tel, //电话
        provinceName: content.province, //省份名称
        cityName: content.city, //市级名称
        regionName: content.county, //区级名称
        detailAddress: content.addressDetail, //详细地址
        defaultFlag: content.isDefault ? 1 : 0, //是否为默认收货地址
      }
      if(state.type == 'edit'){
        params['addressId'] = state.addressId 
      }
      //根据type判断时使用添加接口还是使用编辑接口
      await state.type == 'add' ? addAddress(params) : EditAddress(params)
      Toast('保存成功')
    }

    const addressDetail = async() => {
      const { data: addressDetail } = await getAddressDetail(state.addressId)
      console.log(addressDetail)
      let _areaCode = ''
      const province = window.tdist.getLev1()
      Object.entries(state.areaList.county_list).forEach(([id, text]) => {
        //找出当前对应的区
        if(text == addressDetail.regionName){
          //找到区对应的几个省份
          const provinceIndex = province.findIndex(item=>item.id.substr(0, 2) == id.substr(0, 2))
          //找到区对应的几个市区
          //eslint-disable-next-line no-unused-vars
          const cityItem = Object.entries(state.areaList.city_list).filter(([cityId, cityName]) => cityId.substr(0, 4) == id.substr(0, 4))[0]
          //对比找到的省份和接口返回的省份是否一致，因为有些区会重名
          if(province[provinceIndex].text == addressDetail.provinceName && cityItem[1] == addressDetail.cityName){
            _areaCode = id
          }
        }
      })
      //初始化数据
      state.addressInfo = {
        id: addressDetail.addressId,
        name: addressDetail.userName,
        tel: addressDetail.userPhone,
        province: addressDetail.provinceName,
        city: addressDetail.cityName,
        county: addressDetail.regionName,
        addressDetail: addressDetail.detailAddress,
        areaCode: _areaCode,
        isDefault: !!addressDetail.defaultFlag
      }
    }

    const onDelete =async () => {
      await DeleteAddress(state.addressId)
      Toast('删除成功')
      //操作成功之后，不能马上返回列表，数据清理需要时间
      setTimeout(() =>{
        router.back()
      }, 1000)
    }

    return {
      ...toRefs(state),
      onSave,
      onDelete
    }
  }
}
</script>
<style lang="less">
  @import '../theme/custom';
  .edit{
    .van-field_body{
      textarea{
        height: 26px!important;
      }
    }
  }
  .address-edit-box{
    .van-address-edit{
      .van-button--danger{
        background: @primary;
        border-color: @primary;
      }
      .van-switch--on{
        background: @primary;
      }
    }
  }
</style>